/*
 * Copyright (c) 2014 Strong Group - 版权所有
 * 
 * This software is the confidential and proprietary information of
 * Strong Group. You shall not disclose such confidential information 
 * and shall use it only in accordance with the terms of the license 
 * agreement you entered into with www.cnstrong.cn.
 */
package com.zuorenke.encrypt;


import io.netty.handler.codec.DecoderException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 *
 * 描述:封装各种格式的编码解码工具类.
 * 
 * 1.Commons-Codec的 hex/base64 编码
 * 2.自制的base62 编码
 * 3.Commons-Lang的xml/html escape
 * 4.JDK提供的URLEncoder
 *
 */
public class EncryptUtils {

	private static final String DEFAULT_ENCODING = "UTF-8";

	/**
	 * Md5.
	 */
	public static String md5(byte[] input) {
		return encodeBase64(Digests.md5(input));
	}

	public static String md5(String input) {
		return encodeBase64(Digests.md5(input));
	}

	/**
	 * Base64编码.
	 */
	public static String encodeBase64(byte[] input) {
		return Base64.encodeBytes(input);
	}

	public static String encodeBase64(String encrypt) {
		return encodeBase64(encrypt.getBytes());
	}

	/**
	 * Base64解码.
	 */
	public static byte[] decodeBase64(String input) {
		try {
			return Base64.decode(input);
		} catch (IOException e) {
			return  null;
		}
	}

	public static String decodeBase64ToString(String value) {
		try {
			return new String(decodeBase64(value), DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * URL 编码, Encode默认为UTF-8. 
	 */
	public static String urlEncode(String part) {
		try {
			return URLEncoder.encode(part, DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * URL 解码, Encode默认为UTF-8. 
	 */
	public static String urlDecode(String part) {

		try {
			return URLDecoder.decode(part, DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 转义HTML
	 * @param html
	 * @return
	 */
	public static String htmlEscape(String html) {
		if (html == null || html.trim().length() < 1)
			return "";
		html = html.replaceAll("<", "&lt;");
		html = html.replaceAll(">", "&gt;");
		html = html.replaceAll("'", "&apos;");
		html = html.replaceAll("\"", "&quot;");
		html = html.replaceAll(" ", "&nbsp;");
		return html;
	}

}
